package com.example.lotterysystem.controller;

import com.example.lotterysystem.common.errorcode.ControllerErrorCodeConstants;
import com.example.lotterysystem.common.exception.ControllerException;
import com.example.lotterysystem.common.result.CommonResult;
import com.example.lotterysystem.common.utils.JacksonUtil;
import com.example.lotterysystem.controller.param.ShortMessageLoginParam;
import com.example.lotterysystem.controller.param.UserPasswordLoginParam;
import com.example.lotterysystem.controller.param.UserRegisterParam;
import com.example.lotterysystem.controller.result.UserBaseInfoResult;
import com.example.lotterysystem.controller.result.UserLoginResult;
import com.example.lotterysystem.controller.result.UserRegisterResult;
import com.example.lotterysystem.service.UserService;
import com.example.lotterysystem.service.VerificationCodeService;
import com.example.lotterysystem.service.dto.UserDTO;
import com.example.lotterysystem.service.dto.UserLoginDTO;
import com.example.lotterysystem.service.dto.UserRegisterDTO;
import com.example.lotterysystem.service.enums.UserIdentityEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@RequestMapping("/user")
@RestController
public class UserController {
    // 创建日志类型的对象
    // 这里传入的是 UserController 类，这样就可以创建一个 UserController 类关联的日志记录器
    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private UserService userService;

    @Autowired
    private VerificationCodeService verificationCodeService;

    /**
     * 注册
     * @param param
     * @return
     */
    // 使用这个注解 @Validated 使这个 UserRegisterParam 对象中的属性，进行设置其是否需要输入的特性
    @RequestMapping("/register")
    public CommonResult<UserRegisterResult> userRegister(
            @Validated @RequestBody UserRegisterParam param) {
        // 日志的打印
        logger.info("userRegister UserRegisterParam:{}", JacksonUtil.writeValueAsString(param)); // 将其序列化为一个 String类

        // 调用 Service 层进行处理
        UserRegisterDTO userRegisterDTO = userService.register(param);
        // 将 userRegisterDTO 这个对象 转换成 UserRegisterResult 类，之后进行构造返回对象，是成功类型的信息
        return CommonResult.success(convertToRegisterResult(userRegisterDTO));
    }

    /**
     * 发送验证码
     *
     * @param email
     * @return
     */
    @RequestMapping("/verification-code/send")
    public CommonResult<Boolean> sendVerificationCode(String email) {
        logger.info("sendVerificationCode email:{}", email);
        verificationCodeService.sendVerificationCode(email);

        return CommonResult.success(Boolean.TRUE);
    }

    /**
     * 密码登录
     * @param param
     * @return
     */
    @RequestMapping("/password/login")
    public CommonResult<UserLoginResult> userPasswordLogin(
            @Validated @RequestBody UserPasswordLoginParam param) {
        logger.info("userPasswordLogin UserPasswordLoginParam:{}",JacksonUtil.writeValueAsString(param));
        UserLoginDTO userLoginDTO = userService.login(param);
        return CommonResult.success(convertToLoginResult(userLoginDTO));
    }

    /**
     * 验证码登录
     * @param param
     * @return
     */
    @RequestMapping("/message/login")
    public CommonResult<UserLoginResult> shortMessageLogin(
            @Validated @RequestBody ShortMessageLoginParam param) {
        logger.info("shortMessageLogin ShortMessageLoginParam:{}",JacksonUtil.writeValueAsString(param));
        UserLoginDTO userLoginDTO = userService.login(param);
        return CommonResult.success(convertToLoginResult(userLoginDTO));
    }

    /**
     * 获取人员列表
     * 其中 identity 是可以为null的
     * @param identity
     * @return
     */
    @RequestMapping("/base-user/find-list")
    public CommonResult<List<UserBaseInfoResult>> findUserBaseInfo(String identity) {
        logger.info("findUserBaseInfoList identity:{}",identity);
        List<UserDTO> userDTOList = userService.findUserBaseInfo(UserIdentityEnum.forName(identity));
        // 将这个 List<UserDTO> 转换成 List<UserBaseInfoResult> 之后计科返回了
        return CommonResult.success(convertToList(userDTOList));
    }

    /**
     * 获取人员列表的 中的 返回值类型转换
     * @param userDTOList
     * @return
     */
    private List<UserBaseInfoResult> convertToList(List<UserDTO> userDTOList) {
        if (CollectionUtils.isEmpty(userDTOList)) {
            // 说明 userDTOList 为空，进行返回一个空的 List
            return Arrays.asList();
        }
        // 将 userDTO 转换成 UserBaseInfoResult，进行返回
        return userDTOList.stream()
                .map(userDTO -> {
                    UserBaseInfoResult result = new UserBaseInfoResult();
                    result.setUserName(userDTO.getUserName());
                    result.setUserId(userDTO.getUserId());
                    result.setIdentity(userDTO.getIdentity().name());
                    return result;
                }).collect(Collectors.toList());
    }


    /**
     * 密码 和 验证码 登录的统一返回，修改返回类型
     * @param userLoginDTO
     * @return
     */
    private UserLoginResult convertToLoginResult(UserLoginDTO userLoginDTO) {
        if (userLoginDTO == null) {
            throw new ControllerException(ControllerErrorCodeConstants.LOGIN_ERROR);
        }

        UserLoginResult result = new UserLoginResult();
        result.setToken(userLoginDTO.getToken());
        result.setIdentity(userLoginDTO.getIdentity().name());
        return result;
    }

    /**
     * 注册的修改返回类型
     * @param userRegisterDTO
     * @return
     */
    private UserRegisterResult convertToRegisterResult(UserRegisterDTO userRegisterDTO) {
        UserRegisterResult result = new UserRegisterResult();
        if(userRegisterDTO == null) {
            throw new ControllerException(ControllerErrorCodeConstants.REGISTER_ERROR);
        }
        result.setUserId(userRegisterDTO.getUserId());
        return result;
    }
}
